<template>
    <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
      <CommonDateSearch v-if="initLocationData" ref="searchRef" @search="handleSearch" :extraSearch="extraSearch">
      </CommonDateSearch>
      <div class="content-box">
        <div class="chart-box">
          <Bar class="chart" :loading="loadingRef" :customSelect="customSelect" :customOptions="customOptions" :chartData="chartData" title="外排水量" />
        </div>
        <a-card class="common-card flex table-box" title="外排水量">
          <BasicTable @register="registerTable">
            <template #toolbar>
              <!-- <a-button type="primary" @click="handleDownload" :loading="uploadLoading">导出</a-button> -->
            </template>
          </BasicTable>
  
        </a-card>
      </div>
    </PageWrapper>
  </template>
  <script setup>
  import Bar from '@/components/Charts/Bar/index.vue'
  import { ref, onMounted, reactive } from 'vue'
  import { PageWrapper } from '@/components/Page'
  import CommonDateSearch from '@/components/CommonDateSearch/index.vue'
  import Icon from '@/components/Icon/Icon.vue'
  import { chartChildLisExport, getSingleCaseUsageAndComprehensiveCost } from '@/api/common/chart'
  import { BasicTable, useTable } from '@/components/Table'
  import { getDictListByCode } from '@/api/sys/dict'
  import { message } from 'ant-design-vue'
  
  defineOptions({ name: 'outDrainage' })
  const dictCode = 'water_science_wastewater_system'
  const searchRef = ref()
  const searchInfo = reactive({
    dictCode,
  })
  const loadingRef = ref(true)
  const chartData = ref()
  const locationRef = ref([])
  const initLocationData = ref(false)
  const uploadLoading = ref(false)
  const extraSearch = ref([
    {
      field: 'itemName',
      label: '位置选择',
      component: 'Select',
      show: false,
      colProps: { span: 6 },
      componentProps: ({ formModel }) => {
        formModel.itemName = locationRef.value[0].itemName
        return {
          options: locationRef.value,
          fieldNames: {
            label: 'itemName',
            value: 'itemName',
          }
        }
      },
    },
  ])
  const [registerTable, { setLoading, setColumns, setTableData }] = useTable({//setTableData控制右上角的数据选择
    rowKey: 'id',
    columns: [],
    pagination: false,
    formConfig: {
      labelWidth: 120,
    },
    bordered: true,
    striped: false,
  })
  const customOptions = (options) => {
    let arr = []
    console.log(options, 'options')
    options.forEach(item => {
      if (!arr.find(_item => item.label.indexOf(_item.label) > -1)) {
        arr.push({
          label: item.label,
          value: item.label
        })
      }
    })
    return arr
  }
  onMounted(async () => {
    await getLocationData()
    // searchRef.value.handleSearch()
  })
  const getLocationData = async () => {
    const dictData = await getDictListByCode(dictCode)
    extraSearch.value[0].defaultValue = dictData[0]?.itemName
    locationRef.value = dictData
    initLocationData.value = true
  }
  
  const handleSearch = (params) => {
    Object.assign(searchInfo, params)
    getData()
  }
  
  const formatHeader = (headerData) => {
    const headerList = headerData.map((item) => ({
      title: item,
      dataIndex: item,
      width: 100,
      customRender: ({ text }) => {
        return text || '--'
      },
    }))
    headerList.unshift({
      title: '数据名称',
      dataIndex: 'name',
      width: 250,
      fixed: 'left',
      merge: true,
    })
  
    setColumns(headerList)
  }
  
  const formatTableData = (tableData) => {
    const { xaxisList, yaxisList, codeyAxisList } = tableData
    const data = yaxisList.map((item) => {
      const { data, ...others } = item
      const record = { ...others }
      data.forEach((item, index) => {
        record[xaxisList[index]] = item
      })
      return record
    })
    console.log(data,"???");
    
    setTableData(data)
  }
  
  const getData = () => {
    loadingRef.value = true
    getSingleCaseUsageAndComprehensiveCost({ ...searchInfo})
      .then((res) => {
        console.log(res, "asdw");
  
        chartData.value = res
        formatTableData(res)
        formatHeader(res.xaxisList)
      })
      .finally(() => {
        loadingRef.value = false
      })
  }
  
  const download = (res, name) => {
    var blob = new Blob([res])
    var href = URL.createObjectURL(blob)
    var downloadElement = document.createElement('a')
    downloadElement.href = href
    downloadElement.download = name
    document.body.appendChild(downloadElement)
    downloadElement.click()
    document.body.removeChild(downloadElement)
    URL.revokeObjectURL(href)
  }
  const handleDownload = async () => {
    uploadLoading.value = true
    chartChildLisExport({ ...searchInfo }).then(res => {
      const { data, headers } = res
      let contentDisposition = decodeURIComponent(headers["content-disposition"]);
      const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
      const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
      download(data, fileName);
      message.success("导出成功");
    }).finally(() => {
      uploadLoading.value = false
    })
  
  }
  </script>
  <style scoped lang="scss">
  .content-box {
    display: flex;
    flex: 1;
    flex-direction: column;
    background: #fff;
    overflow: hidden;
    .chart-box {
      padding: 8px 8px 4px;
    }
  
    .chart-box,
    .table-box {
      flex: 1;
      flex-shrink: 0;
      overflow: hidden;
    }
  
    :deep(.ant-table-wrapper) {
      padding: 0;
    }
  }
  </style>
  